﻿Imports System.ServiceModel

Public Class OpenDelib
    Inherits System.Web.UI.MasterPage

    Private Property Token As String
        Get
            Return CStr(Session("TokenConnexion"))
        End Get
        Set(value As String)
            Session("TokenConnexion") = value
        End Set
    End Property
    Public Property Utilisateur As String
        Get
            Return CStr(Session("Utilisateur"))
        End Get
        Private Set(value As String)
            Session("Utilisateur") = value
        End Set
    End Property
    Public ReadOnly Property ScriptManager As ScriptManager
        Get
            Return Me.scriptManagerMaster
        End Get
    End Property
    Public ReadOnly Property UpdatePanel As UpdatePanel
        Get
            Return Me.upMain
        End Get
    End Property

    Public Property Titre As String
        Get
            Return lblTitre.Text
        End Get
        Set(value As String)
            lblTitre.Text = value
        End Set
    End Property

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        CheckAppConnexion()
    End Sub

    Private Sub CheckAppConnexion()
        Dim connected As Boolean = Tools.GetInstance.isConnected()

        If connected Then
            LoadAndInitialize()
            LoadMenu()
        Else
            ConnexionDenied()
        End If

        hfToken.Value = Me.Token
    End Sub

    Private Sub LoadAndInitialize()
        cssmenu.Visible = True
        divTitleBar.Style.Item("width") = "calc(100% - 150px)"
        divContent.Style.Item("width") = "calc(100% - 150px)"
        btnDeco.Visible = True
        btnConnexion.Visible = False
        'btnSettings.Visible = True
    End Sub

    Private Sub ConnexionDenied()
        btnDeco.Visible = False
        If Request.QueryString("deco") <> "1" AndAlso IO.Path.GetFileName(Request.Path).ToLower <> "default.aspx" Then
            Response.Redirect("~/default.aspx?&deco=1&url=" & Tools.Encrypt(Request.RawUrl))
        End If
    End Sub

    Private Sub LoadMenu()
        'Chargement des menu d'applications
        Dim collectionControlesMenu As Dictionary(Of String, HtmlGenericControl) = New Dictionary(Of String, HtmlGenericControl)
        Dim collectionMenuPerso As List(Of ServiceMenu.Menu) = Nothing
        Dim exceptions As List(Of String) = New List(Of String)

        Using svc As New ServiceMenu.MenuPersonnelClient()
            Dim params As New ServiceMenu.ParametresRecupererMenuApplication
            params.Authentication = New ServiceMenu.AuthenticationParameters
            params.Authentication.Token = Token

            params.Utilisateur = Utilisateur

            Dim res As ServiceMenu.RecupererMenuApplicationResult


            res = svc.RecupererMenuApplication(params)
            If res.OK = False Then
                If TypeOf Me.Page Is OpenDelibPage Then
                    CType(Me.Page, OpenDelibPage).NotifyErreur(res.ErrorMessage)
                Else
                    Response.Write(res.ErrorMessage)
                End If
            Else
                collectionMenuPerso = res.Menus
            End If

        End Using


        Dim ulFirst As New HtmlGenericControl("ul")
        ulFirst.Style.Add("height", "100%")

        If collectionMenuPerso IsNot Nothing Then
            'Pour chaque menu personnalisé
            For Each menuPerso As ServiceMenu.Menu In collectionMenuPerso
                If exceptions.Contains(menuPerso.Code) Then Continue For

                Dim li As New HtmlGenericControl("li")
                Dim a As New HtmlGenericControl("a")
                Dim ulSousElements As New HtmlGenericControl("ul")
                Dim labelMenuPerso As New Label

                li.ID = "li_" & menuPerso.Code

                labelMenuPerso.Text = menuPerso.Libelle
                a.Controls.Add(labelMenuPerso)
                a.Attributes.Add("href", "#")
                li.Controls.Add(a)

                If menuPerso.ElementsMenu.Count > 0 Then
                    li.Attributes.Add("class", "active has-sub")
                End If

                For Each elementMenuPerso As ServiceMenu.ElementMenu In menuPerso.ElementsMenu
                    Dim liSousElement As New HtmlGenericControl("li")
                    Dim aElement As New HtmlGenericControl("a")
                    Dim labelSousElement As New Label

                    labelSousElement.Text = elementMenuPerso.Libelle
                    If String.IsNullOrEmpty(elementMenuPerso.Url) Then
                        aElement.Attributes.Add("href", "#")
                    Else
                        If elementMenuPerso.Url.StartsWith("http") Then
                            aElement.Attributes.Add("href", elementMenuPerso.Url)
                        Else
                            aElement.Attributes.Add("href", ResolveUrl(elementMenuPerso.Url))
                        End If

                        If elementMenuPerso.Url.ToLower.Contains("menuapplication.aspx") Then
                            Dim uri As New Uri(Request.Url.GetLeftPart(UriPartial.Authority) & ResolveUrl(elementMenuPerso.Url.ToLower))
                            Dim menu As String = HttpUtility.ParseQueryString(uri.Query).Get("appli").ToUpper
                            If Not exceptions.Contains(menu) Then exceptions.Add(menu)
                            If collectionControlesMenu.ContainsKey(menu) Then
                                ulFirst.Controls.Remove(collectionControlesMenu(menu))
                                collectionControlesMenu.Remove(menu)
                            End If
                        End If
                    End If
                    aElement.Controls.Add(labelSousElement)
                    liSousElement.Controls.Add(aElement)
                    ulSousElements.Controls.Add(liSousElement)
                Next

                li.Controls.Add(ulSousElements)
                ulFirst.Controls.Add(li)
                collectionControlesMenu.Add(menuPerso.Code, li)
            Next
        End If

        cssmenu.Controls.Add(ulFirst)
    End Sub

    Private Sub btnDeco_Click(sender As Object, e As EventArgs) Handles btnDeco.Click
        Tools.GetInstance.deleteToken()
        Response.Redirect("~/Default.aspx")
    End Sub

    Private Sub btnValider_Click(sender As Object, e As EventArgs) Handles btnValider.Click
        Using wsConnect As New ServiceConnexion.ConnexionClient()

            Dim wsAutentificationParameters As New ServiceConnexion.AuthenticationParameters
            wsAutentificationParameters.Password = txtPass.Text
            wsAutentificationParameters.User = txtUser.Text
            wsAutentificationParameters.Token = Token

            Dim paramConnect As New ServiceConnexion.OperationParameters
            paramConnect.Authentication = wsAutentificationParameters

            Try
                Dim result As ServiceConnexion.ConnexionResult = wsConnect.Connect(paramConnect)
                If result.OK Then
                    Token = result.Token
                    Utilisateur = txtUser.Text
                    If Request.QueryString("url") <> "" Then
                        Response.Redirect(Tools.Decrypt(Request.QueryString("url")))
                    Else
                        Response.Redirect("~/Default.aspx")
                    End If
                End If
            Catch ex As Exception
                trErrConnect.Visible = True
                hrErrConnect.Visible = True
                lblErrConnect.Text = ex.Message
            End Try

        End Using
    End Sub

    'Private Sub btnInterface_Click(sender As Object, e As EventArgs) Handles btnInterface.Click
    '    Response.Redirect("~/Default.aspx")
    'End Sub

End Class